import time
import threading
from typing import Dict, List

import logo.Mlog
from process.fsm.FSM import FSM


class FSMMG:
    OK = False

    def __init__(self):
        self.index = 0
        self.curr_state = None
        self.fsms: Dict[int, FSM] = {}

    def add(self, fsm: FSM):
        fsm.index = self.index
        self.fsms[fsm.index] = fsm
        if self.index == 0:
            self.curr_state = fsm
            self.curr_state.start()
        self.index += 1
        logo.Mlog.logger.debug(f"添加状态{fsm.index}")

    def add_multiple(self, fsms: List[FSM]):
        for item in fsms:
            self.add(item)
            # logo.Mlog.logger.debug(f"添加状态{self.fsms[item.index].index}")

    def run(self):
        items = []
        while True:
            # if not FSMMG.OK:
            #     time.sleep(0.1)  # Sleep for a short duration
            #     continue
            self.curr_state.ing()
            kys=list(self.fsms.keys())
            for item in kys:
                if self.fsms[item].condition():
                    items.append(item)
            if len(items) >= 2:
                temp = max(items, key=lambda e: e)
                # logo.Mlog.logger.debug(f"最大状态1={temp}={items}")
                self.cut_state(temp)
                items.clear()
                # logo.Mlog.logger.debug(f"最大状态2={temp}={items}")
            else:
                self.cut_state(0)

            time.sleep(0.1)  # Sleep for a short duration

    @staticmethod
    def set_ok():
        FSMMG.OK = not FSMMG.OK
        print(f"OK2=: {FSMMG.OK}")

    def cut_state(self, item: int):
        # logo.Mlog.logger.debug(f"切换状态1{item}")
        if self.curr_state.index == item :return
        # logo.Mlog.logger.debug(f"切换状态{item}")
        # if not item == 0 :
        #     # logo.Mlog.logger.debug("切换状态失败，必能切换比自己低的状态")and self.curr_state.index > item
        #     return
        self.curr_state.end()
        self.curr_state = self.fsms[item]
        self.curr_state.start()
